package com.dandelion.shiro.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.dandelion.commons.web.model.AjaxResponse;

/**
 * ShiroFormAuthenticationFilter
 */
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {

	/**
	 * 所有请求都会经过的方法。
	 */
	@Override
	protected boolean onAccessDenied(final ServletRequest request, final ServletResponse response) throws Exception {
		
		// 当验证码验证失败时不再走身份认证拦截器。
		if (request.getAttribute(getFailureKeyAttribute()) != null) {
			return true;
		}
		HttpServletRequest httpRequest = WebUtils.toHttp(request);
		HttpServletResponse httpResponse = WebUtils.toHttp(response);
		
		if (isLoginRequest(request, response)) {
			if (isLoginSubmission(request, response)) {
				return executeLogin(request, response);
			} else {
				// 可以访问登录页面
				return true;
			}
		} else {
			if (!"XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) { // 不是ajax请求
				// 保存当前请求并重定向到登录界面
				httpRequest.setAttribute("sessionTimeout", "timeout");
				saveRequestAndRedirectToLogin(httpRequest, httpResponse);
			} else {
				httpResponse.setCharacterEncoding("UTF-8");
				PrintWriter out = null ;
				try {
					out = httpResponse.getWriter() ;
					httpResponse.setStatus(406); //登录超时！！！
					
					AjaxResponse ajaxResponse = new AjaxResponse() ;
					ajaxResponse.setStatus(false);
					ajaxResponse.setMessage("登录超时！请重新登录。");
					out.write(JSON.toJSONString(ajaxResponse));
					
				} catch (IOException ioEx) {
					ioEx.printStackTrace();
				} finally{
					out.flush();
					out.close();
				}
			}
			return false;
		}
	}
}
